<template>
  <div class="watermarker" :style="computedStyle"></div>
</template>
<script>
// 明水印实现
export default {
  props: {
    content: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      canvas: null,
      baseImg: ''
    }
  },
  computed: {
    computedStyle() {
      if(this.baseImg) {
        return {
          background: `url(${this.baseImg}) repeat`
        }
      }
      return {}
    },
  },
  mounted() {
    this.drawText();
  },
  methods: {
    drawText() {
      const dataUrl = this.getDataUrl({text: this.content})
      console.log('dataUrl', dataUrl)
      this.baseImg = dataUrl
    },
    // 获取 toDataURL 的结果
    getDataUrl({
      font = "16px normal",
      fillStyle = "rgba(180, 180, 180, 0.3)",
      textAlign,
      textBaseline,
      text = "请勿外传",
    }) {
      const rotate = -20;
      this.canvas =  this.canvas || document.createElement("canvas");
      const ctx = this.canvas.getContext("2d"); // 获取画布上下文
      ctx.rotate((rotate * Math.PI) / 180);
      ctx.font = font;
      ctx.fillStyle = fillStyle;
      ctx.textAlign = textAlign || "left";
      ctx.textBaseline = textBaseline || "middle";
      ctx.fillText(text, this.canvas.width / 5, this.canvas.height - 20);

      return this.canvas.toDataURL("image/png");
    },
  },
};
</script>
<style lang="scss" scoped>
.watermarker {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 999999;
  pointer-events: none;
  background-size: 200px;
}
</style>
